<template>
    <div class="user-manage">
        <el-row :gutter="10">
            <el-col :span="4" :xs="24">
                <div class="query-form">
                    <el-input placeholder="请输入组织名称" v-model="groupNameFilter" clearable prefix-icon="el-icon-search"
                        style="margin-bottom: 20px"></el-input>
                </div>
                <div class="base-table">
                    <el-tree class="filter-tree" :data="groupList" :props="{ label: 'groupName', children: 'children' }"
                        default-expand-all :filter-node-method="filterNode" @node-click="handleGroupClick"
                        :highlight-current="true" :expand-on-click-node="false" ref="groupTree">
                    </el-tree>
                </div>
            </el-col>
            <el-col :span="20" :xs="24">
                <div class="query-form">
                    <el-form ref="form" :inline="true" :model="user">
                        <el-form-item label="账户" prop="username">
                            <el-input v-model="user.username" placeholder="请输入账户" />
                        </el-form-item>
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="user.name" placeholder="请输入姓名" />
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="user.status">
                                <el-option :value="1" label="正常"></el-option>
                                <el-option :value="0" label="停用"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">查询</el-button>
                            <el-button @click="handleReset('form')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="base-table">
                    <div class="action">
                        <el-button type="primary" @click="handleCreate">新增</el-button>
                        <el-button type="danger" @click="handlePatchDelete">批量删除</el-button>
                    </div>
                    <el-table :data="userList" @selection-change="handleSelectionChange" border cell-style="padding: 4px 0"
                        max-height="600">
                        <el-table-column type="selection" width="40" align="center" />
                        <el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label"
                            :width="item.width" :formatter="item.formatter" align="center" />
                        <el-table-column label="操作" width="200" align="center">
                            <template #default="scope">
                                <el-button size="mini" type="primary" :disabled="scope.row.root"
                                    @click="handleEdit(scope.row)">
                                    编辑</el-button>
                                <el-button size="mini" type="danger" :disabled="scope.row.root"
                                    @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination class="pagination" background layout="prev, pager, next" :total="pager.totalCount"
                        :page-size="pager.pageSize" @current-change="handleCurrentChange" />
                </div>
            </el-col>
        </el-row>
        <el-dialog :title="action == 'add' ? '用户新增' : '用户修改'" v-model="showModal" :close-on-click-modal="false"
            :show-close="false" width="500px" center>
            <el-form ref="dialogForm" :model="userForm" label-width="100px" :rules="rules">
                <el-form-item label="账户" prop="username">
                    <el-input v-model="userForm.username" :disabled="action == 'edit'" placeholder="请输入账户" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="userForm.name" :disabled="action == 'edit'" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="userForm.sex" size="medium" style="width: 100%;" clearable>
                        <el-option label="男" value='0'></el-option>
                        <el-option label="女" value='1'></el-option>
                        <el-option label="保密" value='2'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="电话" prop="phoneNumber">
                    <el-input v-model="userForm.phoneNumber" placeholder="请输入电话" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="userForm.status" style="width: 100%;">
                        <el-option value='1' label="正常"></el-option>
                        <el-option value='0' label="停用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="组织" prop="groupId">
                    <el-cascader v-model="userForm.groupId" :options="groupList" :props="{
                        checkStrictly: true,
                        emitPath: false,
                        value: 'groupId',
                        label: 'groupName',
                    }" clearable style="width:100%" />
                </el-form-item>
                <el-form-item label="角色" prop="roleIds">
                    <el-select v-model="userForm.roleIds" placeholder="请选择角色" value-key="roleId" filterable multiple
                        style="width:100%">
                        <el-option v-for="role in roleList" :key="role.roleId" :label="role.roleName"
                            :value="role.roleId"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, toRaw, watch } from 'vue'
import utils from "../utils/utils";
export default {
    name: 'user',
    setup() {
        // 获取Composition API 上下文对象
        const { ctx, proxy } = getCurrentInstance();
        const groupNameFilter = ref("");
        //初始化用户表单对象
        const user = reactive({});
        //初始化用户列表数据
        const userList = ref([]);
        //全部组织数据
        const groupList = ref([]);
        //初始化分页对象
        const pager = reactive({
            pageNum: 1,
            pageSize: 10
        });
        //选中用户列表的对象
        const checkedUserIds = ref([]);
        //弹框显示对象
        const showModal = ref(false);
        //新增用户表单对象
        const userForm = reactive({});
        //角色列表
        const roleList = ref([]);
        //定义用户操作行为
        const action = ref('add');
        //定义表单校验规则
        const rules = reactive({
            username: [
                {
                    required: true,
                    message: "请输入用户名称",
                    trigger: "blur",
                },
            ],
            name: [
                {
                    required: true,
                    message: "请输入姓名",
                    trigger: "blur",
                },
            ],
            sex: [
                {
                    required: true,
                    message: "请选择性别",
                    trigger: "blur",
                },
            ],
            phoneNumber: [
                {
                    required: true,
                    message: "请输入电话",
                    trigger: "blur",
                },
                {
                    pattern: /1[3-9]\d{9}/,
                    message: "请输入正确的手机号",
                    trigger: "blur",
                }
            ],
            email: [
                {
                    message: "请输入用户邮箱",
                    trigger: "blur"
                },
                {
                    pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                    message: "请输入正确的用户邮箱",
                    trigger: "blur",
                },
            ],
            status: [
                {
                    required: true,
                    message: "请选择状态",
                    trigger: "blur",
                },
            ],
            hiredate: [
                {
                    required: true,
                    message: "请选择入职时间",
                    trigger: "blur"
                },
            ],
            roleIds: [
                {
                    required: false,
                    message: "请选择角色",
                    trigger: "blur",
                },
            ],
        });
        //定义动态表格格式
        const columns = reactive([
            {
                label: '账户',
                prop: 'username',
            },
            {
                label: '姓名',
                prop: 'name',
            },
            {
                label: '性别',
                prop: 'sex',
                width: 50,
                formatter(row, column, value) {
                    return {
                        0: '男',
                        1: '女',
                        2: '保密'
                    }[value]
                }
            },
            {
                label: '手机',
                prop: 'phoneNumber',
                width: 150
            },
            {
                label: '邮箱',
                prop: 'email',
            },
            {
                label: '状态',
                prop: 'status',
                width: 100,
                formatter(row, column, value) {
                    return {
                        1: '正常',
                        0: '停用',
                    }[value]
                }
            },
            {
                label: '注册时间',
                prop: 'createTime',
                formatter(row, column, value) {
                    return utils.formateDate(new Date(value));
                }
            }
        ]);
        //初始化接口调用
        onMounted(() => {
            getUserList();
            getAllRoleList();
            getGroupList();
        })
        const filterNode = (value, data) => {
            if (!value) return true;
            return data.groupName.indexOf(value) !== -1;
        };
        watch(groupNameFilter, val => {
            proxy.$refs["groupTree"].filter(val);
        });
        // 获取用户列表
        const getUserList = async () => {
            let params = { ...user, ...pager };
            try {
                const { list, total } = await proxy.$api.getUserList(params);
                userList.value = list;
                pager.totalCount = total;
            } catch (error) {
                console.log(proxy.$api);
            }
        };
        const getGroupList = async () => {
            try {
                const { list } = await proxy.$api.getGroupList({});
                groupList.value = list;
            } catch (e) {
                throw new Error(e);
            }
        }
        const handleGroupClick = (data) => {
            user.groupId = data.groupId;
            console.log(user.groupId);
            handleQuery();
        };
        //查询事件，获取用户列表
        const handleQuery = () => {
            getUserList();
        }
        // 重置查询表单
        const handleReset = (form) => {
            proxy.$refs[form].resetFields();
            getUserList();
        };
        // 分页事件处理
        const handleCurrentChange = (current) => {
            pager.pageNum = current;
            getUserList();
        };
        //用户单个删除
        const handleDelete = async (row) => {
            await proxy.$api.userDelete({
                userIds: [row.userId]
            })
            proxy.$message.success('删除成功');
            getUserList();
        }
        //批量删除
        const handlePatchDelete = async () => {
            if (checkedUserIds.value.length == 0) {
                proxy.$message.error('请选择要删除的用户');
                return;
            }
            const res = await proxy.$api.userDelete({
                userIds: checkedUserIds.value
            })
            if (res.rows > 0) {
                proxy.$message.success('删除成功');
                getUserList();
            } else {
                proxy.$message.error('删除失败');
            }

        }

        //表格多选
        const handleSelectionChange = (list) => {
            let arr = [];
            list.map(item => {
                arr.push(item.userId);
            })
            checkedUserIds.value = arr;
        }
        //用户新增
        const handleCreate = () => {
            action.value = 'add';
            showModal.value = true;
        }
        // 角色列表查询
        const getAllRoleList = async () => {
            let list = await proxy.$api.getAllRoleList();
            roleList.value = list;
        };
        // 用户弹窗关闭
        const handleClose = () => {
            showModal.value = false;
            handleReset("dialogForm");
        };
        // 用户提交
        const handleSubmit = () => {
            proxy.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    let params = toRaw(userForm);
                    params.action = action.value;
                    if (action.value == 'add') {
                        let res = await proxy.$api.userSubmit(params);
                        proxy.$message.success("用户创建成功");
                    } else {
                        let res = await proxy.$api.userUpdate(params);
                        proxy.$message.success("用户修改成功");
                    }
                    showModal.value = false;
                    handleReset("dialogForm");
                    getUserList();
                }
            });
        };
        // 用户编辑
        const handleEdit = (row) => {
            action.value = "edit";
            showModal.value = true;
            proxy.$nextTick(async () => {
                try {
                    const { user } = await proxy.$api.getUserById({ userId: row.userId });
                    Object.assign(userForm, user);
                } catch (error) {
                    console.log("错误", proxy.$api);
                }
            });
        };
        return {
            groupNameFilter,
            user,
            userList,
            groupList,
            columns,
            pager,
            checkedUserIds,
            showModal,
            userForm,
            roleList,
            action,
            rules,
            filterNode,
            getUserList,
            getGroupList,
            handleGroupClick,
            handleQuery,
            handleReset,
            handleCurrentChange,
            handleDelete,
            handlePatchDelete,
            handleSelectionChange,
            handleCreate,
            getAllRoleList,
            handleClose,
            handleSubmit,
            handleEdit
        }
    }
}
</script>

<style lang="scss"></style>